package com.mediastory.spsserver.guide.service.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.mediastory.spsserver.category.dao.CategoryDao;
import com.mediastory.spsserver.category.domain.Category;
import com.mediastory.spsserver.guideFile.dao.GuideFileDao;
import com.mediastory.spsserver.guideFile.domain.GuideFile;
import com.mediastory.spsserver.guide.dao.GuideDao;
import com.mediastory.spsserver.guide.domain.Guide;
import com.mediastory.spsserver.guide.service.GuideSvc;
import com.Ostermiller.util.Base64;

@Service
@Transactional
public class GuideSvcImpl implements GuideSvc {

	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	GuideDao guideDao;
	
	@Autowired
	GuideFileDao guideFileDao;
	
	@Autowired
	CategoryDao categoryDao;

	public GuideSvcImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Guide> findbyList(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Guide>) (guideDao.SelectList(condition));
	}

	public Map<String, Object> findbyListPaging(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("contentList", (List<Guide>) (guideDao.SelectList(condition)));
		resultMap.put("contentListTotalCnt", (Integer) (guideDao.SelectListTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public Guide findby(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return guideDao.select(condition);
	}
	
	@Override
	public Integer findbyIdx(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return guideDao.selectIdx(condition);
	}

	@Override
	public Guide add(Guide guide) throws Exception {
		// TODO Auto-generated method stub
		Guide result = null;
		List<File> fileList = new Vector<File>();
		
		try {
			result = guideDao.insert(guide);
			
			//파일 업로드
			MultipartFile cFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;
			if(guide.getGuideFiles() != null){
				GuideFile guideFile = new GuideFile();
				
				for(int i = 0;i<guide.getGuideFiles().size();i++){
					cFile = guide.getGuideFiles().get(i);

					//파일의 크기가 0인 경우 넘긴다.
					if(cFile == null || cFile.getSize() == 0){
						continue;
					}
					
					fileType = guide.getGuideFileTypes()[i];
					fileData = guide.getGuideFileDatas()[i];
					fileSize = cFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(guide.getTitle(), "utf-8")+Long.toString(time))) + (1 + (int)(Math.random() * 100));
					//업로드 경로
					String uploadDir = messages.getMessage("file.info.uploadDir");
					//viewUrl
					String viewUrl = messages.getMessage("file.info.viewUrl");
					String fileNm = "";
					String url = "";
					
					//System.out.println(i+fileType);
					
					if(fileType.equals("guideImg")){
						if(cFile != null && ! cFile.isEmpty() && cFile.getContentType().contains("image")){
							fileNm = prefixNm + "_guideImg."+(cFile.getOriginalFilename()).split("\\.")[1];
						}
						fileData = "" + i;
					}else{
						continue;
					}
					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					cFile.transferTo(file);
					
					fileList.add(file);
					
					//콘텐츠 파일 등록
					guideFile.setContIdx(result.getIdx());
					guideFile.setCreatedId(result.getCreatedId());
					guideFile.setCreatedIp(result.getCreatedIp());
					guideFile.setFileUrl(url);
					guideFile.setFileSize(fileSize);
					guideFile.setFileType(fileType);
					guideFile.setFileData(fileData);
					guideFileDao.insert(guideFile);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return result;
	}

	@Override
	public Guide modify(Guide guide) throws Exception {
		// TODO Auto-generated method stub
		List<File> fileList = new Vector<File>();
		
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("contentIdx", guide.getIdx());
			
			//파일 업로드
			condition = new HashMap<String, Object>();
			condition.put("modifiedId", guide.getModifiedId());
			condition.put("modifiedIp", guide.getModifiedIp());
			condition.put("contIdx", guide.getIdx());
			
			MultipartFile cFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;
			if(guide.getGuideFiles() != null){
				GuideFile guideFile = new GuideFile();
				
				for(int i = 0;i<guide.getGuideFiles().size();i++){
					cFile = guide.getGuideFiles().get(i);

					//파일의 크기가 0인 경우 넘긴다.
	 				if(cFile == null || cFile.getSize() == 0){
						continue;
					}
					
					fileType = guide.getGuideFileTypes()[i];
					fileData = guide.getGuideFileDatas()[i];
					fileSize = cFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(guide.getTitle(), "utf-8")+Long.toString(time))) + (1 + (int)(Math.random() * 100));
					//업로드 경로
					String uploadDir = messages.getMessage("file.info.uploadDir");
					//viewUrl
					String viewUrl = messages.getMessage("file.info.viewUrl");
					String fileNm = "";
					String url = "";
					
					if(fileType.equals("guideImg")){
						if(cFile != null && ! cFile.isEmpty() && cFile.getContentType().contains("image")){
							fileNm = prefixNm + "_guideImg."+(cFile.getOriginalFilename()).split("\\.")[1];
						}
						//기존 등록된 파일 데이터 삭제
						condition.put("fileType", "guideImg");
						condition.put("fileData", fileData);
						guideFileDao.delete(condition);
					}else{
						continue;
					}
					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					cFile.transferTo(file);
					
					fileList.add(file);
					
					//콘텐츠 파일 등록
					guideFile.setContIdx(guide.getIdx());
					guideFile.setCreatedId(guide.getModifiedId());
					guideFile.setCreatedIp(guide.getModifiedIp());
					guideFile.setFileUrl(url);
					guideFile.setFileSize(fileSize);
					guideFile.setFileType(fileType);
					guideFile.setFileData(fileData);
					guideFileDao.insert(guideFile);
				}
			}
			
			/*
			//메인 이미지 삭제
			if(guide.getGuideFileIdx() != null){
				condition = new HashMap<String, Object>();
				for(int contFileIdx : guide.getGuideFileIdx()){
					condition.put("idx", contFileIdx);
					guideFileDao.delete(condition);	
				}	
			}
			
			guide = guideDao.update(guide);
			*/
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return guide;
	}

	@Override
	public int remove(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return guideDao.delete(condition);
	}

	@Override
	public Integer findbyChkNm(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return guideDao.SelectListTotalCnt(condition);
	}

}
